package com.tc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @Auther: tianchao
 * @Date: 2022/2/11 09:16
 * @Description:
 */
@Slf4j
public class ChannelFultureTest {
    public static void main(String[] args) throws InterruptedException {
        // 启动器类（启动客户端的）
        ChannelFuture channelFuture = new Bootstrap()
                // 2. 添加 EventLoop:线程配合选择器不断的循环，看看有没有新的事件
                .group(new NioEventLoopGroup())
                // 3 选择客户端channel实现
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //4 处理器
                        ch.pipeline().addLast(new StringEncoder());
                    }
                    // connect 异步非阻塞 真正执行连接的是另一个线程 （NioEventLoopGroup中的线程）
                }).connect(new InetSocketAddress("localhost", 8083));
        //2.1
//        channelFuture.sync();// 同步阻塞方法 直到连接建立
//        Channel channel = channelFuture.channel();//代表连接对象
//        log.debug("channel: {}",channel);
//        channel.writeAndFlush("test");
//        System.out.println("==================");
        //2.2
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("channel: {}",channel);
                channel.writeAndFlush("test");
            }
        });
        System.out.println("==================");
    }
}
